let editForm = null;

$(function() {
  $('body').empty().prepend($(`
  <form id="editForm" method="post">
  <div>
  <button type="button" onclick='addQuestion(event)'>Add Question</button>
  <button type='submit'>Finish</button>
  </div>
</form>`));

  editForm = $('#editForm');
  editForm.submit(function(event) {
    event.preventDefault();
    $.ajax({
      url: 'http://127.0.0.1:8080/questionnaire/add',
      data: htmlToJson(editForm),
      contentType: 'application/json',
      method: 'POST',
      success: [function(data, textStatus, jqXHR) {
        console.log(data);
      }],
      error: [function(jqXHR, textStatus, errorThrown ) {

      }]
    });
  });
});





function addAnswer(e) {
  let ul = $(e.target).next().first();
  let prefix = $(e.target).prev().first().children('input').attr('name');
  let quantity = ul.children().length+1;
  let alias = prefix + '-' + quantity;

  let ulStr = `<li>
  <div>
    <label>Answer ${alias}: <input type='text' name=${alias} required/></label>
    <button type="button" onclick='addQuestion(event)'>Add Question</button>
    </div>
  </li>`;

  ul.append($(ulStr));
}


// e.target: <button>
function addQuestion(e) {
  // grandparent: <form>/<div>
  let grandparent = $(e.target).parent().parent();
  let quantity = grandparent.children().length;
  let alias = quantity;

  // equaling editForm shows that alias should be 1, 2, 3... 
  if(!(grandparent.get(0) === editForm.get(0))) {
    alias = $(e.target).prev().children('input').attr('name') + '-' + quantity;
  }
  
  let editItemStr = `<div>
    <label>Questions ${alias}: <input type='text' name=${alias} required/></label>
    <button type='button' onclick='addAnswer(event)'>Add Answer</button>
    <ul></ul>
  </div>`;

  grandparent.append($(editItemStr));
}

function htmlToJson(form) {
  let inputList = form.find('input');
  let questionnairePrototype = {};

  for (let i=0; i<inputList.length; i++){
    let item = inputList.eq(i);
    questionnairePrototype[item.attr('name')] = item.val();
  }
  
  return JSON.stringify(questionnairePrototype);
}
